<template>
  <div>
    <el-select
      clearable
      @change="changeClear"
      placeholder="请选择省份"
      v-model="province"
    >
      <el-option
        v-for="item in areas"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      style="margin: 0 10px"
      :disabled="!province"
      placeholder="请选择城市"
      v-model="city"
    >
      <el-option
        v-for="item in selectCity"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      placeholder="请选择区域"
      :disabled="!province || !city"
      v-model="area"
    >
      <el-option
        v-for="item in selectArea"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import allAreas from "../lib/pca-code.json";
// 地区数组的类型
export interface AreaItem {
  code: string;
  name: string;
  children?: AreaItem[];
}
export interface Data {
  code: string;
  name: string;
}
// data
let province = ref<string>("");
let city = ref<string>("");
let area = ref<string>("");
//所有数据
let areas = ref<AreaItem[]>(allAreas);
//分发事件给父组件,省市区都值触发
let eimits = defineEmits(["change"]);

// 城市选择数组
let selectCity = computed(() => {
  if (!province.value) return [];
  else {
    city.value = "";
    area.value = "";
    let areasArr = areas.value.find((item) => province.value === item.code);
    return areasArr?.children;
  }
});

// 区域选择数组
let selectArea = computed(() => {
  if (!city.value || !selectCity.value) return [];
  else {
    area.value = "";
    let areasArr = selectCity.value.find((item) => item.code === city.value);
    return areasArr?.children;
  }
});
// watch(()=>province.value,val=>{})  等于   watch(province,(nVal,Oval)=>{})
/**
 * 当区域有数据时候
 */
watch(area, (NewVal, OldVal) => {
  if (!NewVal) return;
  let provinceData: Data = {
    code: province.value,
    name:
      province.value &&
      allAreas.find((item) => {
        return item.code === province.value;
      })!.name, //加！ 表示一定存在
  };
  let cityData: Data = {
    code: city.value,
    name:
      city.value &&
      selectCity.value!.find((item) => {
        return item.code === city.value;
      })!.name,
  };
  let areaData: Data = {
    code: area.value,
    name: selectArea.value!.find((item) => {
      return item.code === area.value;
    })!.name,
  };
  eimits("change", {
    provinceData,
    cityData,
    areaData,
  });
});
// method
let changeClear = (val: string) => {
  if (!val) {
    city.value = "";
    area.value = "";
  }
};
</script>
<style lang="scss" scoped></style>
